package com.java.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.system.entity.Role;
import com.java.system.entity.RoleMenu;
import com.java.system.mapper.RoleMapper;
import com.java.system.mapper.RoleMenuMapper;
import com.java.system.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoman
 * @since 2023-07-21
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RoleMenuMapper roleMenuMapper;
    @Override
    public List<Role> select() {
        LambdaQueryWrapper<Role> queryWrapper=new LambdaQueryWrapper<>();
        List<Role> roleList = roleMapper.selectList(queryWrapper);
        if(!StringUtils.isEmpty(roleList)){
            return roleList;
        }
        else {
            return null;
        }
    }

    @Override
    public void insertRole(Role role) {
        roleMapper.insert(role);
        if(role.getMenuIdList()!=null){
            for(Integer menuId:role.getMenuIdList()){
                roleMenuMapper.insert(new RoleMenu(null,role.getRoleId(),menuId));
            }
        }
    }

    @Override
    public Role selectRoleById(Integer id) {
        Role role = roleMapper.selectById(id);
        List<Integer> menuIdList = roleMenuMapper.getMenuIdListByRoleId(id);
        role.setMenuIdList(menuIdList);

        if(role!=null){
            return role;
        }
        return null;
    }

    @Override
    public void updateRole(Role role) {
        roleMapper.updateById(role);
        //删除角色权限
        LambdaQueryWrapper<RoleMenu> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId,role.getRoleId());
        roleMenuMapper.delete(queryWrapper);
        //新增角色权限
        if(role.getMenuIdList()!=null){
            for(Integer menuId:role.getMenuIdList()){
                roleMenuMapper.insert(new RoleMenu(null,role.getRoleId(),menuId));
            }
        }
    }

    @Override
    public void deleteRole(Integer id) {
        roleMapper.deleteById(id);
        LambdaQueryWrapper<RoleMenu> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId,id);
        roleMenuMapper.delete(queryWrapper);
    }
}
